#include "stdafx.h"
#include "Serializer\BufferSerializer.h"
#include <crtdbg.h>

using namespace persist;

BufferSerializer* BufferSerializer::Create()
{
	return new BufferSerializer;
}

BufferSerializer::BufferSerializer()
{
	buffer = 0;
	m_max_size = 0;
	m_size = 0;

	id_count = 0;

	bOpen=false;
}
BufferSerializer::~BufferSerializer()
{
	
}

void BufferSerializer::serialize(void* data, size_t size)
{
	if(m_size + size > m_max_size)
	{
		_ASSERTE(false);
		return;
	}

	if (mode == READ)
    {
		memcpy(data, (char *)buffer + m_size, size);
		m_size += size;
    }
	else
	{
		memcpy((char *)buffer + m_size, data, size);
		m_size += size;
	}
}
//construct or flush object's data from / to the storage
void BufferSerializer::fill(Persistent* _persistent)
{
	Serializable* serializable=dynamic_cast<Serializable*>(_persistent);
	_ASSERTE(serializable);
	if (serializable) serializable->serialize(*this);
}
//
	//allocate a chunk of storage by identifier and return the given name
std::string BufferSerializer::allocate(const Identifier& _id)
{
	char str[20];
    _ultoa(id_count, str, 10);
	id_count++;
	return std::string(str);
}

void BufferSerializer::bufferOpen(Persistor::Mode _mode, void* mem, unsigned max_size)
{
	mode=_mode;

	buffer = mem;
	m_max_size = max_size;
	m_size = 0;
	bOpen=true;

	if (mode == READ)
	{
		memcpy(&id_count, (char *)buffer, 4);
		m_size += 4;
	}
	else
	{
		m_size += 4;
	}
}

void BufferSerializer::bufferClose(unsigned& size)
{
	if (mode == WRITE) memcpy((char *)buffer , &id_count, 4);
	size = m_size;
	bOpen=false;
	records.clear();
	persistents.clear();
}

